import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import reportWebVitals from './reportWebVitals'
import './public-path'
import {createStore,combineReducers} from 'redux'
import {Provider} from 'react-redux'
let setGlobalState = null

const globalState = (state={},action) => {
  if(action.type === 'setStoreGlobalState'){
    return action.payload
  }
  if(action.type === 'setGlobalState'){
    setGlobalState && setGlobalState(action.payload)
  }
  return state
}
const store = createStore(combineReducers({globalState}))
console.log('store:',store)

function render(props) {
  const { container } = props
  ReactDOM.render(
    <React.StrictMode>
      <Provider store={store}>
        <App />
      </Provider>
    </React.StrictMode>,
    container
      ? container.querySelector('#root')
      : document.querySelector('#root')
  )
}

if (!window.__POWERED_BY_QIANKUN__) {
  render({})
}

export async function bootstrap() {
  console.log('[react16] react app bootstraped')
}

export async function mount(props) {
  console.log('[react16] props from main framework', props)
  setGlobalState = props.setGlobalState
  props.onGlobalStateChange((state, prev) => {
    // state: 变更后的状态; prev 变更前的状态
    console.log('child', state, prev)
    // 微任务
    Promise.resolve().then(()=>{
      store.dispatch({type:'setStoreGlobalState', payload:state})
    })
  })
  store.dispatch({type:'setStoreGlobalState', payload:props.globalState})

  render(props)
}

export async function unmount(props) {
  const { container } = props
  ReactDOM.unmountComponentAtNode(
    container
      ? container.querySelector('#root')
      : document.querySelector('#root')
  )
}

// ReactDOM.render(
//   <React.StrictMode>
//     <App />
//   </React.StrictMode>,
//   document.getElementById('root')
// )

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals()
